package com.impress;

import java.util.Calendar;

import com.mobclick.android.MobclickAgent;
import com.mobclick.android.ReportPolicy;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.util.Log;

public class PreferencesActivity extends PreferenceActivity {

	private static final String TAG = "PreferencesActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		MobclickAgent.onError(this);
		MobclickAgent.setReportPolicy(ReportPolicy.DAILY);
		addPreferencesFromResource(R.xml.preferences);
		Preference lastUpdatePreference = findPreference("last_update");
		if (lastUpdatePreference != null) {
			lastUpdatePreference.setSummary(lastUpdatePreference.getSharedPreferences().getString("last_update_time", ""));
		}
		Preference autoSyncPreference = findPreference("sync_interval");
		if (autoSyncPreference != null) {
			autoSyncPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
				
				@Override
				public boolean onPreferenceChange(Preference preference, Object newValue) {
					Intent intent = new Intent(PreferencesActivity.this, SyncAlarmRecevier.class);
					PendingIntent sender = PendingIntent.getBroadcast(
							PreferencesActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
					int nextTime = (Integer.parseInt(newValue.toString()));
					AlarmManager am = (AlarmManager)PreferencesActivity.this.getSystemService(Context.ALARM_SERVICE);
					am.cancel(sender);
					if (nextTime != 0) {
						Calendar calendar = Calendar.getInstance();
						calendar.add(Calendar.MINUTE, 1);

						long firstTime = calendar.getTimeInMillis();
						am.setRepeating(am.RTC, firstTime, 
								3600*1000*nextTime, sender);
					}
					return true;
				}
			});
		}else {
			Log.d(TAG, "did not find preference");
		}
		
	}	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

}
